package models

import (
	"errors"
	"github.com/beego/beego/v2/client/orm"
	"strings"
	"time"
	"weiboxs.com/new_h_glasses/utils"
)

type DoDiagnosisOften struct {
	Id        int64  `json:"id"`
	Content   string `json:"content"`
	CreatedAt int64  `json:"created_at"`
	Pinyin    string `json:"pinyin"`
	UseNumber int64  `json:"use_number"`
}

func (a *DoDiagnosisOften) TableName() string {
	return DoDiagnosisOftenTableName()
}

func DoDiagnosisOftenTableName() string {
	return TableName("do_diagnosis_often")
}

//查询诊断列表
func DoDiagnosisOftenList(query_str string) []*DoDiagnosisOften {
	query := orm.NewOrm().QueryTable(DoDiagnosisOftenTableName())
	data := make([]*DoDiagnosisOften, 0)
	cond := orm.NewCondition()
	if len(query_str) > 0 {
		cond = cond.Or("content__contains", query_str).Or("pinyin__contains", query_str)
	}
	query.SetCond(cond).OrderBy("-id").All(&data)
	return data
}

//保存常用诊断
func DoDiagnosisOftenSave(content ...string) error {
	if len(content) > 0 {
		o := orm.NewOrm().QueryTable(DoDiagnosisOftenTableName())
		for k, _ := range content {
			model := new(DoDiagnosisOften)
			model.Content = strings.Trim(content[k], " ")
			model.Pinyin = strings.ToLower(utils.ConvertPinyin(model.Content))
			model.CreatedAt = time.Now().Unix()
			model.UseNumber = 1
			if count, _ := o.Filter("content", model.Content).Count(); count > 0 { //已存在
				if _, err := o.Filter("content", model.Content).Update(orm.Params{"UseNumber": orm.ColValue(orm.ColAdd, 1),}); err != nil {
					return err
				}
			} else {
				if _, err := orm.NewOrm().Insert(model); err != nil {
					return err
				}
			}
		}
		return nil
	}
	return errors.New("没有可保存数据")
}
